package com.example.security.dao;

import com.example.security.bean.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserService {
  private final UserDao userDao;

  public UserService(UserDao userDao) {
    this.userDao = userDao;
  }

  @Transactional(propagation = Propagation.REQUIRED)
  public Boolean addUser(User user) {

    if (1 != userDao.addUser(user)) {
      return false;
    }

    // 插入成功, 还需要写入权限
    List<Integer> roleIds = userDao.getRoleIdsByNames(user.getRoles());
    // 增加这个用户的所有权限

    // 应该使用mybatis的批量添加来完成, 不过太过繁琐, 先这么实现
    for (Integer roleId : roleIds) {
      userDao.addUserRole(user.getId(), roleId);
    }

    return true;
  }
}
